package com.oto.web.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.oto.Constants;
import com.oto.DataStatus;
import com.oto.model.AccountDO;
import com.oto.model.FlowDO;
import com.oto.model.PackDO;
import com.sun.jersey.api.view.Viewable;

/**
 * @author xueqiang.mi
 * @since 2010-11-28
 */
@Path("/")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class DefaultResource extends BaseResource {

	public List<AccountDO> getLattestUsers() {
		return accountService.lattest();
	}

	public List<FlowDO> getLattestFlows() {
		return flowService.lattest();
	}

	@GET
	@Path("share")
	public Response share(@DefaultValue("0") @QueryParam("packId") long packId) {
		return Response.ok(new Viewable("share", packId)).build();
	}

	@POST
	@Path("ajax/share")
	@Consumes("application/x-www-form-urlencoded")
	@Produces("text/plain")
	public String doShare(@FormParam("name") String name, @FormParam("content") String content,
			@FormParam("isPublic") boolean isPublic, @FormParam("packId") long packId) {
		PackDO pack = packService.get(packId);
		if (pack == null) {
			return Constants.STATUS_ERROR + " 没有查询到id=[" + packId + "]的电话分组!";
		}
		if (!pack.getOwner().equals(getUserName())) {
			return Constants.STATUS_ERROR + " 您没有对该电话分组的使用权限!";
		}

		FlowDO flow = new FlowDO();
		flow.setName(name);
		flow.setContent(content);
		flow.setDataStatus((isPublic) ? DataStatus.PUBLIC : DataStatus.PRIVATE);
		flow.setPackId(packId);
		flow.setOwner(getUserName());
		flowService.add(flow);
		return Constants.STATUS_DONE;
	}
}
